/**
 * 轨道管理器 - 负责弹幕轨道的分配和管理
 */
import type { BarrageTrack, ActiveBarrage, BarrageConfig } from '../../types'

export class TrackManager {
  private config: BarrageConfig
  private tracks: BarrageTrack[] = []
  private currentTrackIndex = 0

  constructor(config: BarrageConfig) {
    this.config = config
    this.initializeTracks()
  }

  /**
   * 初始化轨道
   */
  private initializeTracks(): void {
    this.tracks = []
    const trackCount = this.config.trackCount || 6
    const canvasHeight = 600 // 默认高度，实际使用时会更新
    const trackHeight = canvasHeight / trackCount

    for (let i = 0; i < trackCount; i++) {
      this.tracks.push({
        index: i,
        y: i * trackHeight,
        height: trackHeight,
        occupied: false,
        lastUsed: 0,
        activeBarrages: [],
        lastBarrageTime: 0
      })
    }
  }

  /**
   * 更新轨道配置
   */
  updateConfig(config: BarrageConfig, canvasHeight: number): void {
    this.config = config
    const trackCount = this.config.trackCount || 6
    
    // 🎬 防挡字幕：底部保留 20% 区域
    const subtitleReservedRatio = this.config.preventSubtitleBlock ? 0.2 : 0
    const availableHeight = canvasHeight * (1 - subtitleReservedRatio)
    const trackHeight = availableHeight / trackCount

    // 重新初始化轨道
    this.tracks = []
    for (let i = 0; i < trackCount; i++) {
      this.tracks.push({
        index: i,
        y: i * trackHeight,
        height: trackHeight,
        occupied: false,
        lastUsed: 0,
        activeBarrages: [],
        lastBarrageTime: 0
      })
    }
  }

  /**
   * 查找可用轨道
   */
  findAvailableTrack(): BarrageTrack | null {
    const fillMode = this.config.trackFillMode || 'normal'
    
    switch (fillMode) {
      case 'sparse':
        return this.findTrackForSparseFill()
      case 'dense':
        return this.findTrackForDenseFill()
      case 'maximum':
        return this.findTrackForMaximumFill()
      case 'round-robin':
        return this.findTrackByRoundRobin()
      default:
        return this.findTrackForNormalFill()
    }
  }

  /**
   * 轮询查找轨道
   */
  private findTrackByRoundRobin(): BarrageTrack | null {
    const startIndex = this.currentTrackIndex
    
    for (let i = 0; i < this.tracks.length; i++) {
      const index = (startIndex + i) % this.tracks.length
      const track = this.tracks[index]
      
      if (this.canPlaceBarrageOnTrack(track)) {
        this.currentTrackIndex = (index + 1) % this.tracks.length
        return track
      }
    }
    
    return null
  }

  /**
   * 最大填充模式
   */
  private findTrackForMaximumFill(): BarrageTrack | null {
    for (const track of this.tracks) {
      if (this.canPlaceBarrageOnTrack(track)) {
        return track
      }
    }
    return null
  }

  /**
   * 密集填充模式
   */
  private findTrackForDenseFill(): BarrageTrack | null {
    const tracksByBarrageCount = [...this.tracks].sort((a, b) => 
      b.activeBarrages.length - a.activeBarrages.length
    )
    
    for (const track of tracksByBarrageCount) {
      if (this.canPlaceBarrageOnTrack(track)) {
        return track
      }
    }
    
    return null
  }

  /**
   * 稀疏填充模式
   */
  private findTrackForSparseFill(): BarrageTrack | null {
    const tracksByBarrageCount = [...this.tracks].sort((a, b) => 
      a.activeBarrages.length - b.activeBarrages.length
    )
    
    for (const track of tracksByBarrageCount) {
      if (this.canPlaceBarrageOnTrack(track)) {
        return track
      }
    }
    
    return null
  }

  /**
   * 正常填充模式
   */
  private findTrackForNormalFill(): BarrageTrack | null {
    for (const track of this.tracks) {
      if (this.canPlaceBarrageOnTrack(track)) {
        return track
      }
    }
    return null
  }

  /**
   * 检查是否可以在轨道上放置弹幕
   */
  private canPlaceBarrageOnTrack(track: BarrageTrack): boolean {
    if (track.activeBarrages.length === 0) {
      return true
    }

    const lastBarrage = track.activeBarrages[track.activeBarrages.length - 1]
    if (!lastBarrage) return true

    const minGap = this.config.minBarrageGap || 20
    const screenWidth = 1920 // 默认宽度，实际使用时会更新
    const lastBarrageRightEdge = lastBarrage.x
    const availableSpace = screenWidth - lastBarrageRightEdge

    return availableSpace > (lastBarrage.width + minGap)
  }

  /**
   * 从轨道移除弹幕
   */
  removeBarrageFromTrack(barrage: ActiveBarrage): void {
    const track = this.tracks[barrage.track]
    if (track) {
      const index = track.activeBarrages.indexOf(barrage)
      if (index !== -1) {
        track.activeBarrages.splice(index, 1)
      }
    }
  }

  /**
   * 添加弹幕到轨道
   */
  addBarrageToTrack(barrage: ActiveBarrage, track: BarrageTrack): void {
    track.activeBarrages.push(barrage)
    track.lastBarrageTime = Date.now()
  }

  /**
   * 获取所有轨道
   */
  getTracks(): BarrageTrack[] {
    return this.tracks
  }

  /**
   * 清空所有轨道
   */
  clearAllTracks(): void {
    this.tracks.forEach(track => {
      track.activeBarrages = []
      track.lastBarrageTime = 0
    })
  }
}

